I dont know how to really explain this, but here my problem.
i have a string "myKey[2]" and i want to
const values = {
"myKey": ["hey", "oh"],
"b": ["something"]
};
const str = "myKey[2]";
My question is : how to get "oh" with a string as a variable name + is there something in js who can read "myarray.key" as variable too without apply many regex and function ?
As the indexing for the array starts from zero, accessing "myKey[2]" will give you undefined.Assuming you want to take the second element from the array,we can do
const values = {
"myKey": ["hey", "oh"],
"b": ["something"]
};
const str = "myKey[1]";
const result=values[str.slice(0, str.indexOf('['))][
Number(str.slice(str.indexOf('[') + 1, str.indexOf(']')))
];
console.log(result);
Your string should be
const str = values.myKey[1];
or if your key has dashes and such
const str = values['myKey'][1];
Keep in mind that the right index in this case is 1, not 2 as the index numbering in arrays starts from 0 and not 1.